#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pthread.h>
#include <math.h>
#include <string.h>

char key_val;//存储从键盘读取的字符

//线程函数
void *key_func ()
{
	key_val = getchar();
	return NULL;
}
int main (int argc, char **argv)
{
	pthread_t pt_key;
	unsigned char data;
	float val;
	int nbytes = 0;
	if (argc < 3) {
		printf ("usage: ./app_pcf8591 /dev/pcf8591 <channel>\n");
		printf ("<channel>:0 1 3\n");
		printf (" 0:brightness\n");
		printf (" 1:temperature\n");
		printf (" 3:volatge\n");
	}

	int fd = open (argv[1], O_RDWR);
	if (fd < 0) {
		perror ("app open error!\n ");
		return -1;
	}

	//线程负责监测标准输入是否有输入，如果有就终止程序
	pthread_create (&pt_key, NULL, key_func, NULL);
	printf ("press 'q' to exit...\n");
	usleep (1000000);

	while (1) {
		//将命令行参数转换为整型
		data = (unsigned char)atoi(argv[2]);
		int channl_val = atoi(argv[2]);
		nbytes = read (fd, &data, 1);
		nbytes = write (fd, &data, 1);

		//使用滑动变阻器模拟温度传感器
		if (channl_val == 3) {
			val = (float)data * (3.3/255);
			//val = val * 7.7;
			float temp_val = 100 - val*30.3;
			printf ("ADC%d = %.3fV\r\n", atoi(argv[2]), val);
			printf ("temp_val = %0.f\n", temp_val);
		}
		
		if (channl_val == 0) {
			val = (float)data * (3.3/255);
			float light_intensity = 100 - (val-0.8)*44;
			printf ("val = %.2f\n", val);
			printf ("light = %.0f\n", light_intensity);
		}

		usleep (2000000);
		if (key_val == 'q') {
			break;
		}
	}
	close (fd);
	system ("rmmod i2c_pcf8591");
	//线程的会合（收尸）
	pthread_join (pt_key, NULL);
	return 0;
}
